package edu.csl.study.springboot.mongo.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

/**
 * MongoDB的两种方法：
 *  1、本类的MongoTemplate
 *  2、UserDemoDao的继承PagingAndSortingRepository类
 *    支持方法名关键字查询
 */
@Service
public class MongoTemplateServiceImpl {
	 protected static final Logger logger = LoggerFactory.getLogger(MongoTemplateServiceImpl.class);
	 @Autowired
	 private MongoTemplate mongoTemplate;
	 
	 public <T> T save(T obj,boolean ignoreError) {
		if(obj == null) {
			 return null;
		}
		try {
			 return mongoTemplate.save(obj);
			 
		} catch (Exception e) {
			//忽略异常
			if(ignoreError) {
				logger.error("存储对象{}时出现系统异常（忽略异常）：{}",obj.getClass().getSimpleName(),e.getMessage(),e);
			}else {
				throw new RuntimeException("存储对象{"+obj.getClass().getSimpleName()+"}时出现系统异常。",e);
			}
		}
		return obj;
	 }
	 public <T> T save(T obj,String collectionName,boolean ignoreError) {
			if(obj == null) {
				 return null;
			}
			try {
				 return mongoTemplate.save(obj,collectionName);
				 
			} catch (Exception e) {
				//忽略异常
				if(ignoreError) {
					logger.error("存储对象{}时出现系统异常（忽略异常）：{}",obj.getClass().getSimpleName(),e.getMessage(),e);
				}else {
					throw new RuntimeException("存储对象{"+obj.getClass().getSimpleName()+"}时出现系统异常。",e);
				}
			}
			return obj;
	}
	
}